# -*- coding:utf-8 -*-
# 该代码包含了两个烟雾传感器的处理
import RPi.GPIO as GPIO
import serial
import time
import csv
import struct
import requests
import json
from requests import exceptions
import redis

url = "http://192.168.195.1:7550/api/fog"
headers = {
  'Content-Type': 'application/json'
}
REDIS_CONFIG = {
    'host': 'localhost',  # IP
    'port': 6379,  # 端口
    'password': '',  # 密码
    'db': 0,  # 数据库
    'decode_responses': True # 将存入的数据进行解码（主要用于将bytes类型转成string类型）
}
r = redis.StrictRedis(**REDIS_CONFIG)
ser1 = serial.Serial("/dev/ttyUSB2", 9600, timeout=0.01)  # receive data once every 0.1S 
ser1.flushInput()

ser2 = serial.Serial("/dev/ttyUSB3", 9600, timeout=0.01)  # receive data once every 0.1S 
ser2.flushInput()

data1 = ""
data2 = ""

send_status1 = True
send_status2 = True

data_count1 = 0 #redis计数
data_count2 = 0

redis_data1 = [] #redis数据
redis_data2 = []

for i in range(120): #初始化
    redis_data1.append({"fog": str(0)})
    redis_data2.append({"fog": str(0)})

V1= 0.0 # A0电压值（损失了低2位精度）
V2= 0.0 # A0电压值（损失了低2位精度）

pmm1 = 0.0
pmm2 = 0.0

f = "./lucky.csv"
line = 0
connect_flag = 1
recover_flag = 0
feedback = struct.pack("BBB",0xaa,0x55,0x01)

print("You can always receive data, press Ctrl + C to exit")
with open(f,"w+") as csvfile: 
    while 1: 
        #烟雾传感器1
        if ser1.inWaiting() > 0:
            data1 = ser1.readline()
            if data1 != "":
                if data1[0]==170 and data1[1]==85 and data1[2]==6:
                    ser1.write(feedback)
                    if data1[3]==0:
                    # 收到一次烟雾的值就给一个反馈：aa 55 1
                        if data_count1==120:
                            data_count1 = 0
                        ser1.flush()
                        V1 = 5.0*(data1[4]*4.0)/1024.0  #实际的电压值
                        pmm1 = pow(11.5428 * 35.904 * V1/(25.5-5.1* V1),0.6549) #换算后的浓度值 
                        #发送实时数据
                        payload = json.dumps({"value": [{"fog": str(pmm1),"type":6}]})
                        try:
                            response = requests.request("POST", url, headers=headers, data=payload,timeout=)
                        except Exception:
                        #redis缓存存储
                        redis_data1[data_count1]={"fog": str(pmm1)}
                        old_data1 = json.dumps({"value": redis_data1,"type":6})
                        r.set("fog1", old_data1) 
                        data_count1+=1
                        # #服务器宕机，发送历史数据
                        if response.status_code != 200:
                            response = requests.request("POST", url, headers=headers, data=r.get("fog1"))
                    #树莓派宕机
                    if data1[3]==1:
                        fog1 = []
                        for i in range(3,len(data1),4):
                            V1 = 5.0*(data1[i]*4.0)/1024.0  #实际的电压值
                            pmm1 = pow(11.5428 * 35.904 * V1/(25.5-5.1* V1),0.6549) #换算后的浓度值 
                            fog1.append({"fog": str(pmm1)})
                        #发送历史数据
                        payload = json.dumps({"value": fog1,"type":6})
                        response = requests.request("POST", url, headers=headers, data=payload)
        #烟雾传感器2
        if ser2.inWaiting() > 0:
            data2 = ser2.readline()
            if data2 != "":
                if data2[0]==170 and data2[1]==85 and data2[2]==7:
                    ser2.write(feedback)
                    if data2[3]==0:
                    # 收到一次烟雾的值就给一个反馈：aa 55 1
                        if data_count2==120:
                            data_count2 = 0
                        ser2.flush()
                        V2 = 5.0*(data2[4]*4.0)/1024.0  #实际的电压值
                        pmm2 = pow(11.5428 * 35.904 * V2/(25.5-5.1* V2),0.6549) #换算后的浓度值 
                        #发送实时数据
                        payload = json.dumps({"value": [{"fog": str(pmm2),"type":7}]})
                        response = requests.request("POST", url, headers=headers, data=payload)
                        #redis缓存存储
                        redis_data2[data_count2]={"fog": str(pmm2)}
                        old_data2 = json.dumps({"value": redis_data2,"type":7})
                        r.set("fog2", old_data2) 
                        data_count2+=1
                        #服务器宕机，发送历史数据
                        if response.status_code != 200:
                            response = requests.request("POST", url, headers=headers, data=r.get("fog2"))
                    #树莓派宕机
                    if data2[3]==1:
                        fog2 = []
                        for i in range(3,len(data2),4):
                            V2 = 5.0*(data2[i]*4.0)/1024.0  #实际的电压值
                            pmm2 = pow(11.5428 * 35.904 * V2/(25.5-5.1* V2),0.6549) #换算后的浓度值 
                            fog2.append({"fog": str(pmm2)})
                        #发送历史数据
                        payload = json.dumps({"value": fog2,"type":7})
                        response = requests.request("POST", url, headers=headers, data=payload)

                        
                            
